class Movie < ActiveRecord::Base
  validates_presence_of :title, :description, :message => "is needed!"
  validates_length_of :description, :minimum => 10, :too_short => "is too short!"
  validates_uniqueness_of :title, :message => "corresponds to an existing movie!"
  validates_inclusion_of :rating, :in => %w[G PG PG-13 R NC-17], :message => "is not a valid rating!"
  
  def to_param
    "#{id}-#{title.gsub(/[^a-z0-9]+/i, '-').downcase}"
  end
  
  # Returns a formatted version of the date:
  def release_date
    return self.released_on.strftime('%B %d, %Y')
  end
  
  def self.required_age_for
    return {
      "G"     =>  0,
      "PG"    =>  0,
      "PG-13" =>  13,
      "R"     =>  17,
      "NC-17" =>  17
    }
  end
  
  def appropriate_for_birthdate?(birthdate)
    required_birthdate = Movie.required_age_for[self.rating].years.ago
    return required_birthdate > birthdate
  end
  
  def self.find_all_appropriate_for_birthdate(birthdate)
    @movies = Movie.find(:all)
    return @movies.select do |movie|
      movie.appropriate_for_birthdate?(birthdate)
    end
  end
end
